package cn.ug.account.service.impl;

import cn.ug.account.bean.RoleBean;
import cn.ug.account.mapper.RoleAuthorizeMappingMapper;
import cn.ug.account.mapper.RoleMapper;
import cn.ug.account.mapper.entity.Role;
import cn.ug.account.mapper.entity.RoleAuthorizeMapping;
import cn.ug.account.service.RoleService;
import cn.ug.aop.RemoveCache;
import cn.ug.aop.SaveCache;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.status.DeleteStatus;
import cn.ug.core.ensure.Ensure;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.UF;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static cn.ug.config.CacheType.OBJECT;
import static cn.ug.config.CacheType.SEARCH;

/**
 * @author kaiwotech
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl implements RoleService {
	
	@Resource
	private RoleMapper roleMapper;
	@Resource
	private RoleAuthorizeMappingMapper roleAuthorizeMappingMapper;

	@Resource
	private DozerBeanMapper dozerBeanMapper;

	@Override
	@RemoveCache(cleanSearch = true, cleanService = {AuthorizeServiceImpl.class})
	@Transactional
	public int save(RoleBean entityBean, String[] authorizeIds) {
		// 数据完整性校验
		if(null == entityBean || StringUtils.isBlank(entityBean.getName())) {
			Ensure.that(true).isTrue("11000201");
		}
		// 判断数据是否已经存在
		if(exists(entityBean, entityBean.getId())){
			Ensure.that(true).isTrue("00000004");
        }

		Role entity = dozerBeanMapper.map(entityBean, Role.class);

		if(StringUtils.isBlank(entity.getId())) {
			entity.setId(UF.getRandomUUID());
		}
		int rows = roleMapper.insert(entity);
		Ensure.that(rows).isLt(1, "00000005");

		// 添加关联信息
		if(null != authorizeIds && authorizeIds.length > 0) {
			List<RoleAuthorizeMapping> roleAuthorizeMappingList = new ArrayList<>();
			for (String authorizeId : authorizeIds) {
				RoleAuthorizeMapping o = new RoleAuthorizeMapping();
				o.setId(UF.getRandomUUID());
				o.setRoleId(entity.getId());
				o.setAuthorizeId(authorizeId);

				roleAuthorizeMappingList.add(o);
			}

			rows = roleAuthorizeMappingMapper.insertBatch(roleAuthorizeMappingList);
			Ensure.that(rows).isLt(1, "00000005");
		}


        return 0;
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0, cleanService = {AuthorizeServiceImpl.class})
	@Transactional
	public int update(String id, RoleBean entityBean, String[] authorizeIds) {
        // 数据完整性校验
		if(null == entityBean || StringUtils.isBlank(entityBean.getId()) || StringUtils.isBlank(entityBean.getName())) {
			Ensure.that(true).isTrue("11000201");
		}
		// 该数据已存在
		if(exists(entityBean, entityBean.getId())){
			Ensure.that(true).isTrue("00000004");
        }
		Role entity = roleMapper.findById(entityBean.getId());
		dozerBeanMapper.map(entityBean, entity);

		int rows = roleMapper.update(entity);
		Ensure.that(rows).isLt(1, "00000005");

		// 移除关联信息
		roleAuthorizeMappingMapper.deleteByRoleId(entityBean.getId());

		// 添加关联信息
		if(null != authorizeIds && authorizeIds.length > 0) {
			List<RoleAuthorizeMapping> roleAuthorizeMappingList = new ArrayList<>();
			for (String authorizeId : authorizeIds) {
				RoleAuthorizeMapping o = new RoleAuthorizeMapping();
				o.setId(UF.getRandomUUID());
				o.setRoleId(entity.getId());
				o.setAuthorizeId(authorizeId);

				roleAuthorizeMappingList.add(o);
			}

			rows = roleAuthorizeMappingMapper.insertBatch(roleAuthorizeMappingList);
			Ensure.that(rows).isLt(1, "00000005");
		}
		return 0;
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int delete(String id) {
		if(StringUtils.isBlank(id)) {
			return 0;
		}

		return roleMapper.delete(id);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int deleteByIds(String[] id){
		if(id == null || id.length<=0){
			return 0;
		}

		return roleMapper.deleteByIds(id);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int removeByIds(String[] id) {
		if(id == null || id.length<=0){
			return 0;
		}

		return roleMapper.updateByPrimaryKeySelective(
				getParams()
						.put("id", id)
						.put("deleted", DeleteStatus.YES)
						.toMap()
		);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public boolean exists(RoleBean entityBean, String id) {
		if(null == entityBean || StringUtils.isBlank(entityBean.getName())) {
			return false;
		}

		int rows = roleMapper.exists(
				getParams()
						.put("name", entityBean.getName())
						.put("id", id)
						.toMap()
		);
		return rows > 0;
	}

	@Override
	@SaveCache(cacheType = OBJECT)
	public RoleBean findById(String id) {
		if(StringUtils.isBlank(id)) {
			return null;
		}

		Role entity = roleMapper.findById(id);
		if(null == entity) {
			return null;
		}

		RoleBean entityBean = dozerBeanMapper.map(entity, RoleBean.class);
		entityBean.setAddTimeString(UF.getFormatDateTime(entity.getAddTime()));
		entityBean.setModifyTimeString(UF.getFormatDateTime(entity.getModifyTime()));
		return entityBean;
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public List<RoleBean> findList(String order, String sort, Integer status,String keyword) {
		return query(order, sort, status, keyword);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public DataTable<RoleBean> query(String order, String sort, int pageNum, int pageSize, Integer status,String keyword){
		Page<RoleBean> page = PageHelper.startPage(pageNum, pageSize);
		List<RoleBean> list = query(order, sort, status, keyword);
		return new DataTable<>(page.getPageNum(), page.getPageSize(), page.getTotal(), list);
	}

	@Override
	@RemoveCache(cleanSearch = true, cleanObjectByKeyPosition = 0)
	public int updateStatus(String[] id, Integer status) {
		if(id == null || id.length<=0){
			return 0;
		}

		return roleMapper.updateByPrimaryKeySelective(
				getParams()
						.put("id", id)
						.put("status", status)
						.toMap()
		);
	}

	/**
	 * 获取数据列表
	 * @param order			排序字段
	 * @param sort			排序方式 desc或asc
	 * @param status		状态	 0：全部 1：正常 2：禁用
	 * @param keyword		关键字
	 * @return				列表
	 */
	private List<RoleBean> query(String order, String sort, Integer status,String keyword){
		List<Role> list = roleMapper.query(
				getParams(keyword, order, sort)
						.put("status", status)
						.toMap());
		return toBean(list);
	}

	@Override
	@SaveCache(cacheType = SEARCH)
	public List<RoleBean> findListByPersonnel(String personnelId) {
		List<Role> list = roleMapper.findListByPersonnel(personnelId);
		return toBean(list);
	}

	private List<RoleBean> toBean(List<Role> list) {
		List<RoleBean> dataList = new ArrayList<>();
		if(null == list || list.isEmpty()) {
			return dataList;
		}
		for (Role o : list) {
			RoleBean objBean = dozerBeanMapper.map(o, RoleBean.class);
			objBean.setAddTimeString(UF.getFormatDateTime(o.getAddTime()));
			objBean.setModifyTimeString(UF.getFormatDateTime(o.getModifyTime()));
			dataList.add(objBean);
		}
		return dataList;
	}
}

